<template>
  <div>
    <Header
      :left="true"
      leftText="返回"
      title="修改关闭加严申请"
      v-if="!this.isAdd"
    />
    <Header
      :left="true"
      leftText="返回"
      title="新增关闭加严申请"
      v-if="this.isAdd"
    />

    <!-- 滑动区域，适应手机分辨率 -->
    <div class="textScroll">
      <div class="divMessage">
        <van-field
          readonly
          class="formstyle"
          name="picker"
          :value="valueMachineID"
          label="生产线:"
          placeholder="点击选择生产线"
          @click="showPickerMachineID = true"
          style="font-weight: bold"
        />

        <van-popup v-model="showPickerMachineID" position="bottom">
          <van-picker
            show-toolbar
            :columns="searchColumns"
            @confirm="onConfirmMachineID"
            @cancel="showPickerMachineID = false"
          >
            <template #option="option">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                "
              >
                <div>{{ option.MachineID }}</div>
              </div>
            </template>
            <template #title>
              <van-field
                v-model="searchKey"
                placeholder="请输入搜索内容"
                clearable
              />
            </template>
          </van-picker>
        </van-popup>
        <Field
          v-model="a"
          v-if="this.isAdd"
          size="small"
          class="Field"
          center
          colon
          label="加严管控记录ID"
          placeholder="选择加严管控记录ID"
          label-width="110px"
          @click.stop="confirmmessage(item)"
        />

        <Field
          v-model="item.AddStrictIDList"
          v-if="!this.isAdd"
          size="small"
          class="Field"
          center
          colon
          label="加严管控记录ID"
          placeholder="选择加严管控记录ID"
          label-width="110px"
        />

        <Field
          class="formstyle"
          v-model="b"
          :readonly="true"
          name="加严管控描述"
          label="加严管控描述"
          placeholder="自动带出"
          rows="2"
          autosize
          type="textarea"
          maxlength="4000"
          show-word-limit
          label-width="110px"
        />
      </div>
      <!-- 基本信息 -->
      <van-row style="margin-top: 10px"> </van-row>
      <div class="divMessage">
        <Field
          v-model="item.RequestMan"
          size="small"
          class="Field"
          center
          colon
          label="申请人"
          placeholder="请输入申请人"
          label-width="110px"
        />
        <Field
          v-model="item.ReqDescription"
          rows="2"
          autosize
          type="textarea"
          label="申请描述:"
          placeholder="请输入申请描述"
          class="Field1"
          label-width="110px"
        />
        <Field
          v-model="item.RequestReason"
          rows="2"
          autosize
          type="textarea"
          label="申请关闭理由:"
          placeholder="请输入申请关闭理由"
          class="Field1"
          label-width="110px"
        />
        <!-- <van-field readonly class="formstyle" name="picker" v-model="valueQualityCheckRecord" label="实验室检验记录:"
          placeholder="点击选择实验室检验记录" @click="showPickerQualityCheckRecord = true" style="font-weight: bold" /> -->

        <van-popup v-model="showPickerQualityCheckRecord" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnsQualityCheckRecord"
            @confirm="onConfirmQualityCheckRecord"
            @cancel="showPickerQualityCheckRecord = false"
          >
            <template #option="option">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                "
              >
                <div>{{ option.SheetID }}</div>
              </div>
            </template>
          </van-picker>
        </van-popup>
        <Field
          :readonly="true"
          class="formstyle"
          name="checkres"
          @click="showCamera"
          label="点击拍照上传"
          placeholder="————点击拍照————"
          right-icon="assets/right.png"
        />
        <div
          class="formstyle"
          v-if="
            equipRepairVo1.picList !== undefined &&
            equipRepairVo1.picList.length > 0
          "
        >
          <div
            style="margin-left: 15px; margin-bottom: 15px"
            class="formstyle"
            v-for="(imgUrl, ks) in equipRepairVo1.picList"
            :key="ks"
          >
            <div class="van-uploader__wrapper" style="float: left">
              <div class="van-uploader__preview">
                <div
                  @click="picShow(ks)"
                  class="van-image van-uploader__preview-image"
                >
                  <img :src="imgUrl" class="van-image__img" />
                </div>
                <div
                  class="van-uploader__preview-delete"
                  @click="delObj('pic', imgUrl)"
                >
                  <i
                    class="van-icon van-icon-cross van-uploader__preview-delete-icon"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- <div style="margin: 14px" v-if="this.status == false">
          <van-button color="#138087" round block type="info" native-t qype="submit"
            @click="selectDetails(item)">查看加严管控详情</van-button>
        </div> -->
        <div style="margin: 14px" v-if="this.status == false">
          <van-button
            color="#138087"
            round
            block
            type="info"
            native-type="submit"
            @click="submitCheck()"
            >确认提交</van-button
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  Icon,
  NoticeBar,
  Button,
  Row,
  Tag,
  Checkbox,
  Pagination,
  popup,
  Loading,
  Popup,
  Panel,
  ImagePreview,
  Toast,
  tab,
  tabs,
  Divider,
  Image as VanImage,
  Field,
  CellGroup,
  Cell,
  Picker,
  Uploader,
  Dialog,
  Col,
  RadioGroup,
  Radio,
} from "vant";
import { _httpClient as _httpClientApi } from "@/libs/api";
import { _httpClient } from "@/libs/apisie";
import { storage } from "@/libs/utils";
import {
  removeToken,
  getToken,
  setBaseApiFrefix,
  getBaseApiFrefix,
} from "@/libs/auth";
Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(tab);
Vue.use(tabs);
Vue.use(Button);
Vue.use(Col);
Vue.use(Row);
Vue.use(Icon);
Vue.use(VanImage);
Vue.use(Divider);
Vue.use(Checkbox);
Vue.use(Pagination);
Vue.use(Panel);
Vue.use(Dialog);
Vue.use(Picker);
Vue.use(popup);
Vue.use(Uploader);
Vue.use(Loading);
Vue.use(Field);
Vue.use(RadioGroup);
Vue.use(Radio);
Vue.use(ImagePreview);
import Header from "@/components/header.vue";
import apicloud from "@/libs/apicloud";
export default {
  name: "tightcloseitem01",

  components: {
    Button,
    NoticeBar,
    Header,
    ImagePreview,
    Icon,
    Row,
    tab,
    popup,
    Popup,
    tabs,
    Tag,
    VanImage,
    Toast,
    Divider,
    Field,
    CellGroup,
    Cell,
    Uploader,
    Picker,
    Dialog,
    Col,
    RadioGroup,
    Radio,
  },

  data() {
    return {
      searchKey: "",
      searchKey1: "",
      searchColumns: [],
      showPickerQualityCheckRecord: false,
      showPickerMachineID: false,
      equipRepairVo1: {
        eqKey: null,
        equipName: "",
        equipCode: "",
        remark: null,
        picList: [],
        videoList: [],
        audioList: [],
        requestTime: this.getNowTime(),
        requestUser: "",
      },
      btnLoading: false,
      winName: "", //窗口名
      user: [], //当前登录用户
      form: {},
      itemsOne: [],
      a: "",
      b: "",
      valueMachineID: "",
      valueQualityCheckRecord: "",
      faultTypes: [],
      stopReson: [],
      uploadSuccess: false,
      columnsDealType: [],
      columnsEmployee: [],
      columnsQProblem: [],
      columnsshift: [],
      showPickerEmployee: false,
      showPickerQProblem: false,
      item: {},
      valuepDealTypeName: "",
      EmployeeName: "",
      time: "",
      FactoryID: "",
      valuepShiftName: "",
      CheckTypeName: "",
      QProblemName: "",
      valueteamid: "",
      nowDate: "",
      EmployeeID: "",
      result: [],
      //领班
      QCLeaderAgreeValue: "",
      //带版主管
      TeamLeaderAgreeValue: "",
      //质量负责人
      QCManagerAgreeValue: "",
      //生产部门负责人
      PrdManagerAgreeValue: "",
      //利润点负责人
      FactoryManagerAgreeValue: "",
      //当前状态
      status: "",
      //是否显示人员
      showEmployee: false,
      isAdd: "",
    };
  },
  created: function () {
    // alert("ss")
    let item = api.pageParam.item;
    this.user = JSON.parse(storage.get("user"));
    let oldHight = api.winWidth;
    this.screenWidth = oldHight;
    this.getMachineID();
    this.getQualityCheckRecord();
    if (item == null) {
      this.status = api.pageParam.status;
      this.nowDate = this.getNowTime();
      this.isAdd = api.pageParam.isAdd;
    } else {
      this.item = item;
      this.b = this.item.StrictDescription;
      this.a = this.item.AddStrictIDList;
      this.isAdd = api.pageParam.isAdd;
      this.valueQualityCheckRecord = this.item.LaboratoryCheckRecord;
      this.valueMachineID = this.item.PLineID;
    }

    if (this.isAdd) {
      this.item.RequestMan = this.user.userName;
    }
  },
  mounted() {
    api.addEventListener(
      {
        name: "flush-close-00",
      },
      (ret, err) => {
        this.itemsOne = ret.value.itemsOne;

        let list = [];
        let list2 = [];
        for (let i = 0; i < this.itemsOne.length; i++) {
          list.push(this.itemsOne[i].Id);
          list2.push(
            this.itemsOne[i].Id + "-" + this.itemsOne[i].StrictDescription
          );
        }
        this.item.FactoryID = this.itemsOne[0].FactoryID;
        this.item.AddStrictIDList = list.join(";");
        this.a = this.item.AddStrictIDList;
        this.item.StrictDescription = list2.join(";");
        this.b = this.item.StrictDescription;
      }
    );
  },
  watch: {
    //实时监听搜索输入内容
    searchKey: {
      handler(newVal) {
        let key = String(newVal);
        //alert(key);
        key = key.replace(/\s*/g, "");
        const reg = new RegExp(key, "ig");
        /* 进行筛选，将筛选后的数据放入新的数组中，‘name’键可根据需要搜索的key进行调整 */
        this.searchColumns = this.columnsMachineID.filter(
          (item) => item.MachineID.match(reg) != null
        );
        //alert(this.searchColumns);
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    async getQualityCheckRecord() {
      let _this = this;
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() + "/QualityCheckRecord/GetList"
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            SheetID: item.SheetID,
            Id: item.Id,
          }));
          _this.columnsQualityCheckRecord = teamMap;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async getMachineID() {
      let _this = this;
      try {
        let res = await _httpClient.get(
          _httpClient.getApiPrefix() + "/MachineEquipment/GetList"
        );
        if (res.HttpCode === "200") {
          let teamMap = res.Data.map((item) => ({
            MachineID: item.PlineID,
          }));
          teamMap = _this.uniqueJSON(teamMap, "MachineID");
          _this.columnsMachineID = teamMap;
          _this.searchColumns = teamMap;
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    uniqueJSON(arr, attrName) {
      let obj = {};
      let result = arr.reduce((previousValue, currentValue) => {
        (obj[currentValue[attrName]]
          ? ""
          : (obj[currentValue[attrName]] = true)) &&
          previousValue.push(currentValue);
        return previousValue;
      }, []);
      return result;
    },
    onConfirmMachineID(value, index) {
      this.valueMachineID = this.searchColumns[index].MachineID;
      this.form.MachineID = this.searchColumns[index].MachineID;
      this.showPickerMachineID = false;
      this.getDataCollectionItemID(this.columnsMachineID[index].MachineID);
    },
    onConfirmQualityCheckRecord(value, index) {
      this.valueQualityCheckRecord = this.columnsQualityCheckRecord[index].Id;
      this.form.QualityCheckRecord =
        this.columnsQualityCheckRecord[index].SheetID;
      this.showPickerQualityCheckRecord = false;
      //this.getDataCollectionItemID(this.columnsMachineID[index].MachineID);
    },
    getNowTime() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      return dateTime;
    },
    getNowTimeplus() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      return dateTime;
    },
    async sendmessage() {
      let _this = this;

      let eventDescription = "";
      let eventDatetime = _this.getNowTimeplus();
      let eventTypeID = "N3";
      let eventID = "";
      let messageContent = "";
      let msgContentTypeID = "";
      let pLineID = "";
      let machineID = "";
      let pShiftID = "";
      let teamID = "";
      let pOrderID = "";
      let productionBarcode = "";
      let materialBarcode = "";
      let relatedEmployee = "";
      let messageStatus = "";
      let processBatchID = "";
      let beginDatetime = _this.getNowTimeplus();
      let sendFinished = false;
      let closed = false;

      msgContentTypeID = "ADS04";
      eventID = "ADS04";
      eventDescription = "加严管控:" + _this.item.Id + "已关闭";
      messageContent =
        "加严管控:" +
        _this.item.Id +
        "已关闭，请质检人员关注变化，采用合适的检验模板进行检测";

      let bodysss = {
        eventDescription: eventDescription,
        eventDatetime: eventDatetime,
        eventTypeID: eventTypeID,
        eventID: eventID,
        messageContent: messageContent,
        msgContentTypeID: msgContentTypeID,
        factoryID: "TC00",
        pLineID: pLineID,
        machineID: machineID,
        pShiftID: pShiftID,
        teamID: teamID,
        pOrderID: pOrderID,
        productionBarcode: productionBarcode,
        materialBarcode: materialBarcode,
        relatedEmployee: relatedEmployee,
        messageStatus: messageStatus,
        processBatchID: processBatchID,
        beginDatetime: beginDatetime,
        sendFinished: sendFinished,
        closed: closed,
      };
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/RealtimeEventMessage/SaveEntity",
          {
            body: bodysss,
          }
        );
        //alert(JSON.stringify(res));
        if (res.Message == null) {
          Toast.clear();
          Toast.success("发送成功");

          api.openWin({
            name: "tightclose",
            url: "./tightenup-tightclose.html",
            reload: true,
          });
          setTimeout(function () {
            _this.$ac.closeWin();
          }, 2000);
        } else {
          Toast.clear();
          Toast.fail("发送失败");
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    async sendmessage2() {
      let _this = this;

      let eventDescription = "";
      let eventDatetime = _this.getNowTimeplus();
      let eventTypeID = "N3";
      let eventID = "";
      let messageContent = "";
      let msgContentTypeID = "";
      let pLineID = "";
      let machineID = "";
      let pShiftID = "";
      let teamID = "";
      let pOrderID = "";
      let productionBarcode = "";
      let materialBarcode = "";
      let relatedEmployee = "";
      let messageStatus = "";
      let processBatchID = "";
      let beginDatetime = _this.getNowTimeplus();
      let sendFinished = false;
      let closed = false;

      msgContentTypeID = "ADS06";
      eventID = "ADS06";
      eventDescription = "加严关闭申请单:" + _this.item.Id + "已创建";
      messageContent =
        "加严管控:" + _this.item.Id + "已创建，请质量制程主管进行审批！";
      let bodysss = {
        eventDescription: eventDescription,
        eventDatetime: eventDatetime,
        eventTypeID: eventTypeID,
        eventID: eventID,
        messageContent: messageContent,
        msgContentTypeID: msgContentTypeID,
        factoryID: "TC00",
        pLineID: pLineID,
        machineID: machineID,
        pShiftID: pShiftID,
        teamID: teamID,
        pOrderID: pOrderID,
        productionBarcode: productionBarcode,
        materialBarcode: materialBarcode,
        relatedEmployee: relatedEmployee,
        messageStatus: messageStatus,
        processBatchID: processBatchID,
        beginDatetime: beginDatetime,
        sendFinished: sendFinished,
        closed: closed,
      };

      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/RealtimeEventMessage/SaveEntity",
          {
            body: bodysss,
          }
        );

        if (res.Message == null) {
          Toast.clear();
          Toast.success("发送成功");

          api.openWin({
            name: "tightclose",
            url: "./tightenup-tightclose.html",
            reload: true,
          });
          setTimeout(function () {
            _this.$ac.closeWin();
          }, 2000);
        } else {
          Toast.clear();
          Toast.fail("发送失败");
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    picShow(pIndex) {
      ImagePreview({
        images: this.equipRepairVo1.picList || [],
        showIndicators: true,
        startPosition: pIndex || 0,
        showIndex: false,
      });
    },
    showCamera() {
      let that = this;
      //alert("手机系统"+api.deviceName.toLowerCase());
      //判断设备系统类型
      if (api.systemType == "ios") {
        that.iosCamera();
      } else {
        if (api.deviceName.toLowerCase() == "vivo") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "oppo") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "oneplus") {
          that.oppoReno2Camera();
        } else if (api.deviceName.toLowerCase() == "honor") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "xiaomi") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "meizu") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "realme") {
          that.vivoCamera();
        } else if (api.deviceName.toLowerCase() == "huawei") {
          // that.vivoCamera();
          // that.otherCamera();
          that.vivoCamera();
          // that.otherCameraPlus();
        } else if (api.deviceName.toLowerCase() == "ptac") {
          that.vivoCamera();
        } else {
          that.vivoCamera();
          // that.otherCameraPlus();
          // that.otherCamera();
        }
      }
    },

    vivoCamera() {
      let that = this;
      var FNPhotograph = api.require("FNPhotograph");
      FNPhotograph.open(
        {
          album: false,
          quality: "high",
          isShowAlbum: false,
          // useAdvanceFeature: true,
          // pictureSize: '2075x1080',
          // previewSize: '2075x1080',
        },
        function (ret) {
          if (ret && ret.eventType == "takePhoto") {
            let imgSrc = ret.imagePath;
            if (imgSrc && imgSrc != "") {
              FNPhotograph.close();
              that.imageFilter(imgSrc);
            }
          }
        }
      );
    },

    xiaomiCamera() {
      let that = this;
      var cameraTool = api.require("cameraTool");
      cameraTool.openCamera(function (ret, err) {
        let imgPath = ret.imgPath;
        if (imgPath && imgPath != "") {
          that.imageFilter(imgPath);
        }
      });
    },
    oppoReno2Camera() {
      let _this = this;
      api.getPicture(
        {
          sourceType: "camera",
          encodingType: "jpg",
          mediaValue: "pic",
          allowEdit: false,
          destinationType: "url",
          quality: 50,
        },
        function (ret, err) {
          // 获取拍照数据并处理
          if (ret) {
            let imgSrc = ret.data;
            if (imgSrc && imgSrc != "") {
              _this.imageFilter(imgSrc);
            }
          }
        }
      );
    },
    otherCamera() {
      let that = this;
      // var cameraTool = api.require('cameraTool')
      // cameraTool.openCamera(function(ret, err) {
      //   let imgPath = ret.imgPath
      //   if (imgPath && imgPath != '') {
      //     that.imageFilter(imgPath)
      //   }
      // })
      var module = api.require("easyCamera");
      var param = {
        typeString: "image", // 或者'video-20'
      };
      var resultCallback = function (ret, err) {
        var msg = ret.msg;
        if (msg && msg != "") {
          that.imageFilter(msg);
        }
      };
      module.openCamera(param, resultCallback);
    },
    otherCameraPlus() {
      let that = this;
      var ox = api.require("oxWxRecorder");
      ox.getPermission(function (ret) {
        var code = ret.code;
        if (code == 1) {
          ox.open(
            {
              fixedOn: api.frameName,
              rect: { x: 0, y: 0, w: w, h: h },
              fixed: true,
              type: 2, //0拍照录像 1 录像 2 拍照
            },
            function (ret1) {
              var code1 = ret1.code;
              if (code1 == 0) {
                //关闭事件
              } else if (code1 == 2) {
                //返回图片路径path
                that.imageFilter(ret1.path);
              } else if (code1 == -1) {
                //错误信息
                alert(ret1.text);
              }
            }
          );
        }
      });
    },
    iosCamera() {
      let that = this;
      let zySmallVideo = api.require("zySmallVideo");
      zySmallVideo.openNew(
        {
          rect: {
            //模块 附于一个frame之上
            x: 0,
            y: 0,
            w: api.frameWidth,
            h: api.frameHeight,
          },
          fixedOn: api.frameName,
          fixed: true,
          videoInfo: {
            setOutputFormat: 2, //录制格式 默认2 mp4  0（DEFAULT） 1（THREE_GPP） 2（MPEG_4默认） 3（RAW_AMR） 4（AMR_WB） 5（AAC_ADIF） 6（AAC_ADTS） 7（OUTPUT_FORMAT_RTP_AVP） 8（OUTPUT_FORMAT_MPEG2TS） 9（WEBM）
            setVideoEncoder: 2, //编码格式 默认2 h264 0（DEFAULT） 1（H263） 2（H264默认） 3（MPEG_4_SP） 4（VP8） 5（HEVC）
            setAudioEncoder: 3, //音频格式应该是 默认3 aac  0（DEFAULT） 1（AMR_NB） 2（AMR_WB） 3（AAC默认） 4（HE_AAC） 5（AAC_ELD） 6（VORBIS）
          },
          MaxRecordTime: 60, //最大录制时间 单位秒 默认10
          MinRecordTime: 5, //最短录制时间  单位s
          MinTimeText: "时间不能小于5秒，不能大于60秒", //最短时间提示词
          setFeatures: 1001, //设置拍照和录像   1001只拍照   1002只录像   1003两者都可以  默认1003
          setTip: "", //设置按钮上的提示词   长按拍摄等 默认空
          setBackIcon: "", //自定义返回图标 默认向下键头  支持widget  fs 等路径图片
          setBackShow: 1, //设置返回图标是否显示 1是 0否  默认1
          setCameraIcon: "", //自定义切换摄像头图标  支持widget  fs 等路径图片
          setCameraShow: 1, //右上角切换摄像头是否显示 1是 0否 默认1
          cameraInfo: {
            //摄像头 设置样式
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            margin_l: 0, //距左 默认都是0
            margin_r: 35, //距右
            margin_t: 65, //距上
            margin_b: 0, //距下
          },
          foucsInfo: {
            //点击的对焦框 样式
            color: "#cd0000", //线条颜色 默认16AE16
            width: 4, //线条宽度 默认4
          },
          recordInfo: {
            progress_color: "#cd0000", //进度条颜色 默认16AE16
            outside_color: "#DCDCDC", //外圆背景色 默认DCDCDC
            inside_color: "#FFFFFF", //内圆背景色 默认FFFFFF
          },
          confirmInfo: {
            //确认框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
          cancelInfo: {
            //取消框参数
            fit_xy: false, //图片是否拉伸占满宽高  默认false
            img: "", //设置自定义图片
          },
        },
        function (ret, err) {
          if (ret.status) {
            if (ret.type == "captureSuccess") {
              that.imageFilter(ret.result);
            }
          }
        }
      );
    },

    //图片压缩
    imageFilter(imgPath) {
      let that = this;
      var imageFilter = api.require("imageFilter");
      var imageCachePath = api.cacheDir; //cache://协议对应的真实目录，字符串类型
      imageFilter.compress(
        {
          img: imgPath,
          quality: 0.5,
          size: "800X600",
          save: {
            album: false,
            imgPath: imageCachePath + "/",
            imgName: "cs.jpg",
          },
        },
        function (ret, err) {
          let imgUrl = imageCachePath + "/cs.jpg";
          that.getFileName("pic", imgUrl);
          //文件删除
          var fs = api.require("fs");
          fs.remove(
            {
              path: imgPath,
            },
            function (ret, err) {
              if (ret.status) {
              } else {
              }
            }
          );
        }
      );
    },
    //获取文件名称
    async getFileName(fType, fUrl) {
      let type = "jpg";
      if (fType === "audio") {
        type = "amr";
      } else if (fType === "video") {
        type = "mp4";
      } else if (fType === "pic") {
        type = "jpg";
      } else if (fType === "audio2") {
        type = "aac";
      }
      let res = await _httpClient.get(
        _httpClientApi.getApiPrefix() +
          "/minio/oss/getFileName?fileType=" +
          type
      );
      if (res.code === 200) {
        //上传文件
        this.putObj(fType, fUrl, res.fileName);
      }
    },

    //定时器
    timeCycle(fType, fileName) {
      let that = this;
      let cycleNum = 0;
      that.uploadSuccess = false;
      let intervald = setInterval(() => {
        if (
          that &&
          !that._isDestroyed &&
          cycleNum < _httpClient.getUploadCycle() &&
          !that.uploadSuccess
        ) {
          setTimeout(() => {
            if (that && !that._isDestroyed) {
              that.queryFileUpload(fType, fileName);
              cycleNum++;
            }
          }, 0);
        } else {
          //清除定时器
          clearInterval(intervald);
          that.uploadSuccess = true;
          Toast.clear();
          if (cycleNum == _httpClient.getUploadCycle()) {
            alert("上传超时，请重试");
          }
        }
      }, 2000);
    },

    //查询文件是否上传成功
    async queryFileUpload(fType, fileName) {
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "校验保存中...",
      });
      let that = this;
      let res = await _httpClient.get(
        _httpClientApi.getApiPrefix() + "/minio/oss/" + fileName
      );
      if (res.code === 200) {
        let urls = res.objectURL.split("?");
        if (urls.length > 0) {
          if (fType === "audio") {
            that.equipRepairVo.audioList.push(urls[0]);

            let newList2 = [];
            that.equipRepairVo.audioList.forEach((item) => {
              // 空数组newList2 不包含item为false ,取反为true 执行数组添加操作
              // 如果数组包含了 item为true 取反为false 不执行数组添加操作
              if (!newList2.includes(item)) {
                newList2.push(item);
              }
            });

            that.equipRepairVo.audioList = newList2;
            // that.equipRepairVo.audioList = that.equipRepairVo.audioList.filter(function (item, index) {
            //   return arr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
            // });
          } else if (fType === "video") {
            that.equipRepairVo.videoList.push(urls[0]);

            let newList2 = [];
            that.equipRepairVo.videoList.forEach((item) => {
              // 空数组newList2 不包含item为false ,取反为true 执行数组添加操作
              // 如果数组包含了 item为true 取反为false 不执行数组添加操作
              if (!newList2.includes(item)) {
                newList2.push(item);
              }
            });
            that.equipRepairVo.videoList = newList2;

            // that.equipRepairVo.videoList = that.equipRepairVo.videoList.filter(function (item, index) {
            //   return arr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
            // });
          } else if (fType === "pic") {
            that.equipRepairVo1.picList.push(urls[0]);

            let newList2 = [];
            that.equipRepairVo1.picList.forEach((item) => {
              if (!newList2.includes(item)) {
                newList2.push(item);
              }
            });

            that.equipRepairVo1.picList = newList2;
          } else if (fType === "audio2") {
            that.equipRepairVo.audioList.push(urls[0]);

            let newList2 = [];
            that.equipRepairVo.audioList.forEach((item) => {
              // 空数组newList2 不包含item为false ,取反为true 执行数组添加操作
              // 如果数组包含了 item为true 取反为false 不执行数组添加操作
              if (!newList2.includes(item)) {
                newList2.push(item);
              }
            });

            that.equipRepairVo.audioList = newList2;
            // that.equipRepairVo.audioList = that.equipRepairVo.audioList.filter(function (item, index) {
            //   return arr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个
            // });
          }

          Toast("上传成功");
        }
        Toast.clear();
        that.uploadSuccess = true;
      }
    },

    //文件上传
    putObj(fType, fUrl, fileName) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "上传中...0%",
      });
      api.ajax(
        {
          url:
            _httpClientApi.getApiPrefix() +
            "/minio/oss/appPutObject?fileName=" +
            fileName,
          //  url: 'http://192.168.2.102:8083' + '/minio/oss/putObject',
          method: "post",
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          report: true,
          data: {
            files: {
              file: fUrl,
            },
          },
        },
        function (ret, err) {
          if (ret) {
            Toast.loading({
              mask: true,
              forbidClick: true,
              duration: 0,
              message: "上传进度...\n" + ret.progress + "%",
            });
            if (ret.body.code === 200) {
              if (api.systemType == "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            } else if (ret.progress == 100) {
              if (api.systemType != "ios") {
                _this.timeCycle(fType, fileName);
                //文件删除
                var fs = api.require("fs");
                fs.remove(
                  {
                    path: fUrl,
                  },
                  function (ret, err) {
                    if (ret.status) {
                    } else {
                    }
                  }
                );
              }
            }
          } else {
            Toast.clear();
          }
        }
      );
    },
    async delObj(fType, fUrl) {
      this.commitLoading = false;
      let fname = "";
      try {
        if (fUrl != undefined && fUrl != "" && fUrl != null) {
          fname = fUrl.substring(fUrl.lastIndexOf("/") + 1);
        }
        let res = await _httpClient.delete(
          _httpClientApi.getApiPrefix() + "/minio/oss/" + fname
        );
        if (res.code === 200) {
          let flist = [];
          if (fType === "audio") {
            flist = this.equipRepairVo1.audioList;
          } else if (fType === "video") {
            flist = this.equipRepairVo1.videoList;
          } else if (fType === "pic") {
            flist = this.equipRepairVo1.picList;
          }
          if (flist.length > 0) {
            for (var i = 0; i < flist.length; i++) {
              if (flist[i] == fUrl) {
                flist.splice(i, 1);
              }
            }
          }
          Toast.success(res.msg);
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
    //确认
    async confirmmessage(item) {
      if (this.valueMachineID == "") {
        Toast("请先选择生产线");
        return;
      }

      item.isAdd = this.isAdd;
      api.openWin({
        name: "heyu5",
        url: "./employee-heyu5.html",
        pageParam: {
          item: item,
          form: {},
          isAdd: this.isAdd,
          machineId: this.form.MachineID,
        },
      });
    },
    async selectDetails(item) {
      api.openWin({
        name: "tightcloseitem02",
        url: "./tightenup-tightcloseitem02.html",
        pageParam: {
          item: item,
        },
        reload: true,
      });
    },
    //保存
    submitCheck() {
      var body = {};
      body = this.item;
      if (this.item.Creator == "" || this.item.Creator == null) {
        body.Creator = this.user.userName;
      }
      body.Modifytor = this.user.userName;
      body.ModifyDatetime = this.getNowTime();
      body.ImageURL = String(this.equipRepairVo1.picList);
      body.laboratoryCheckRecord = this.valueQualityCheckRecord;
      body.pLineID = this.form.MachineID;

      //alert(JSON.stringify(body));
      this.SaveCheckEntity(body);
    },
    async SaveCheckEntity(body) {
      let _this = this;
      Toast.loading({
        mask: true,
        forbidClick: true,
        duration: 0,
        message: "请稍等...",
      });
      try {
        let res = await _httpClient.post(
          _httpClient.getApiPrefix() + "/AddStrictCloseRequest/SaveEntity",

          {
            body: body,
          }
        );
        if (res.Message != null) {
          //message不为空,有报错信息，打卡失败 暂时这样判断
          Toast.clear();
          Toast.fail("保存失败,请核对信息！");
        } else {
          // alert(JSON.stringify(res))
          this.item.Id = res.Data;
          //打卡成功
          Toast.clear();
          Toast.success("保存成功！");
          // _this.sendmessage();
          _this.sendmessage2();
        }
      } catch (e) {
        Toast.fail(JSON.stringify(e));
      }
    },
  },
};
</script>
<style>
html,
body {
  font-family: "Open Sans", sans-serif;
  background-color: White;
}

.mg5 {
  margin-right: 5px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.container.dwo {
  display: flex;
  justify-content: center;
  align-items: center;
}

.tag_margin {
  margin: 2px 5px;
}

.card_under {
  height: 100%;
  width: 100%;
  margin: auto;
  background: #ffffff;
  border-radius: 25px;
  box-shadow: 0 0px 0px rgba(0, 0, 0, 0.3);
}

.confirmReport {
  position: fixed;
  right: 5px;
  bottom: 24px;
  width: 48%;
  height: 40px;
  font-size: 12px;
}

.concelReport {
  position: fixed;
  left: 5px;
  bottom: 24px;
  width: 48%;
  height: 40px;
  font-size: 12px;
}

.card_icon {
  text-align: center;
  /* position: absolute; */
  height: 8rem;
  width: 80%;
  margin: 12% 10%;
  background: rgba(35, 180, 237, 1);
  border-radius: 25px;
  box-shadow: 0 10px 50px rgba(0, 0, 0, 0.3);
}

.text {
  font-size: 18px;
  color: #4e4a67;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 600;
}

.text_small {
  font-size: 16px;
  color: red;
  margin: 8px auto auto 20px;
  line-height: 1.5rem;
  text-align: justify;
  font-weight: 700;
}

.text_scan {
  font-size: 16px;
  color: #4e4a67;
  margin: auto auto auto 20px;
  line-height: 1.5em;
  text-align: justify;
}

.textScroll {
  display: inline-block;
  position: fixed;
  top: 4rem;
  bottom: 2px;
  overflow: scroll;
  right: 0;
  width: 100%;
  margin-bottom: 0rem;
  z-index: 1;
}

.divStyle {
  /* border: 1px solid #dcdcdc; */
  border-top-width: 3px;
  border-left-width: 3px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 4px;
}

.buttonRight {
  position: fixed;
  margin-top: -40px;
  right: 15px;
  width: 90px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}

.buttonLeft {
  position: fixed;
  margin-top: -40px;
  right: 110px;
  width: 90px;
  height: 40px;
  background-color: #1c6c8d;
  border-color: #1c6c8d;
}
</style>
